﻿using System.Threading;
using Primitive.Mvvm.Framework.Interfaces;
using UIController.ViewModels;

namespace UIController.Controllers
{
    internal class TimerController
    {
        //fuck
        //set == signaled, resource is free
        //reset == non-signaled, resource is locked
        private Thread _reminderThread;
        private ManualResetEventSlim _stopEvent = new ManualResetEventSlim(true, 100);//signalled, i.e. free to use
        private IMediator _mediator;

        public TimerController(IMediator mediator)
        {
            _mediator = mediator;
        }

        public void StartReminders(IModel model)
        {
            StopReminders();

            var worker = new ThreadExecutiveViewModel(model, _mediator, _stopEvent);
            if(_reminderThread == null)
            {
                _reminderThread = new Thread(worker.DoWork);
            }
            
            _stopEvent.Reset();//non-signalled - locked
            _reminderThread.Start();
        }

        internal void StopReminders()
        {
            if (_reminderThread != null)
            {
                _stopEvent.Set();
                _reminderThread.Join();    
            }
        }
    }
}
